package com.example.boot.modules.marketing.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.boot.modules.marketing.convert.CarouseConvert;
import com.example.boot.modules.marketing.entity.Carousel;
import com.example.boot.modules.marketing.entity.CarouselItem;
import com.example.boot.modules.marketing.mapper.CarouselItemMapper;
import com.example.boot.modules.marketing.mapper.CarouselMapper;
import com.example.boot.modules.marketing.service.ICarouselService;
import com.example.boot.modules.marketing.vo.CarouselVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 轮播图配置
 * </p>
 *
 * @author 王令
 * @since 2024-02-27
 */
@Service
@RequiredArgsConstructor
public class CarouselServiceImpl extends ServiceImpl<CarouselMapper, Carousel> implements ICarouselService {

    private final CarouselItemMapper itemMapper;

    @Override
    @Transactional
    public boolean removeById(Serializable id) {
        itemMapper.delete(Wrappers.<CarouselItem>lambdaQuery().eq(CarouselItem::getCarouselId, id));
        return super.removeById(id);
    }

    @Override
    public CarouselVo getByCode(String code) {
        Carousel carousel = baseMapper.selectOne(Wrappers.<Carousel>lambdaQuery()
                .eq(Carousel::getCode, code)
                .eq(Carousel::getEnabled, true)
                .last("limit 1")
        );
        if (ObjUtil.isNull(carousel)) {
            return null;
        }
        List<CarouselItem> items = itemMapper.selectList(Wrappers.<CarouselItem>lambdaQuery()
                .eq(CarouselItem::getCarouselId, carousel.getId())
                .eq(CarouselItem::getEnabled, true)
        );
        CarouselVo carouselVo = CarouseConvert.INSTANCE.toVo(carousel);
        carouselVo.setItems(items);
        return carouselVo;
    }
}
